<template>
   <div class="header" style="height: 60px">
      <div class="header__top">
         <div class="sidebar"
            v-if="currentPath == '/platformManagement/home' || currentPath == '/platformManagement/productManagement/product'">
            <a href="/" class="top">
               <img src="https://cgj-1309034514.cos.ap-chengdu.myqcloud.com/202410/67107e3adc80e.png"
                  class="top__logo" />

               <span>进销存管理系统</span>
            </a>
         </div>

         <div class="header__top__left">
            <!-- <el-icon @click="clickicon" v-if="isCollapse">
               <Expand />
            </el-icon>
            <el-icon @click="clickicon" v-else>
               <Fold />
            </el-icon> -->
            <span class="header__top__left__txt">
               <el-menu background-color="#E6E7EE" ellipsis class="el-menu-popper-demo" mode="horizontal"
                  :default-active="String(routerIndex)" :popper-offset="16" style="max-width: 100%"
                  active-text-color="#6860FF">
                  <el-menu-item :index="String(index)" v-for="(item, index) in menuData" :key="index"
                     @click="clickRoter(item, index)">{{ item.title }}
                  </el-menu-item>
               </el-menu>
            </span>
         </div>
         <div class="header__top__right">
            <div class="header__top__right__left">
               <!-- <img src="@/assets/images/tz.png" alt="" class="left_imgs"> -->
               <el-badge :value="12" class="item notification-badge">
                  <div class="notification-icon">
                     <img src="../assets/tz.png" class="left_imgs hoverShow" alt="" />
                     <div class="tooltip">通知中心</div>
                  </div>
               </el-badge>

               <div class="fullscreen-icon">
                  <img v-if="isFullScreen" @click="handleClickQp" src="../assets/qp.png" class="left_imgs hoverShow"
                     style="margin-right: 0px" alt="" />
                  <img v-else @click="handleClickQp" src="../assets/sx2.png" class="left_imgs hoverShow"
                     style="margin-right: 0px" alt="" />
                  <div class="tooltip">{{ isFullScreen ? "进入全屏" : "退出全屏" }}</div>
               </div>
            </div>

            <div class="header__top__right__center" style="margin: 0 20px; color: #00000069">
               {{ "|" }}
            </div>

            <div class="header__top__right__right">
               <div class="avatar-container">
                  <img src="https://fuss10.elemecdn.com/e/5d/4a731a90594a4af544c0c25941171jpeg.jpeg"
                     class="header__top__right__right__img hoverShow" alt="" />
                  <div class="avatar-preview">
                     <img src="https://fuss10.elemecdn.com/e/5d/4a731a90594a4af544c0c25941171jpeg.jpeg" alt="" />
                  </div>
               </div>

               <div class="username-container">
                  <div class="hoverShow">{{ userName }}</div>
                  <div class="user-menu">
                     <div class="menu-item" @click="handleChangePassword"><i class="el-icon-key"></i> 修改密码</div>
                     <div class="menu-item" @click="Logout">
                        <i class="el-icon-switch-button"></i> 退出登录
                     </div>
                  </div>
               </div>
            </div>
         </div>
      </div>

      <!-- 加载进度条 -->
      <div class="loading-progress" :style="{ width: `${loadingProgress}% `, opacity: `${opacity}` }"></div>
      <!-- 修改代码弹窗 -->
      <UpdatePassword ref="UpdatePasswordRef" />
   </div>
</template>

<script setup>
import { ref, watchEffect, computed, onMounted } from "vue";
import api from "@/api";
import { usePublicDataStore } from "@/stores";
import { useRouterStore } from "@/stores";
import { useRouter, useRoute } from "vue-router";
import { ElMessage } from "element-plus";
import UpdatePassword from "@/views/UpdatePassword.vue";
const UpdatePasswordRef = ref(null);
const dropdownRefs = ref([]);
const publicDataStore = usePublicDataStore();
const ruterStore = useRouterStore();
const cgj = inject("cgj");
const route = useRoute();
const router = useRouter();

// 使用过滤后的菜单数据，而不是完整的路由列表
const menuData = ref([]);
const emit = defineEmits(["clickicon", "clickMenu"]);

const props = defineProps({
   leftWidth: {
      type: [Number, String],
      default: 200,
   },
});
let routerIndex = ref(0);
const userName = ref("未登录");
const loadingProgress = ref(0);
const opacity = ref(0);
onMounted(async () => {
   const userInfo = JSON.parse(localStorage.getItem("userInfo"));
   if (userInfo) {
      userName.value = userInfo.nickname; // 假设用户信息中有 name 字段
   }

   // 获取用户权限过滤后的菜单数据
   try {
      const filteredMenus = await ruterStore.filterMenuList();
      menuData.value = filteredMenus || [];
      console.log('过滤后的菜单数据:', menuData.value);
   } catch (error) {
      console.error('获取菜单数据失败:', error);
      // 如果获取失败，使用空数组，不显示任何菜单
      menuData.value = [];
   }
});
let currentPath = ref(route.path);
let timer = null;
watch(
   () => route.path,
   (newVal, oldVal) => {
      currentPath.value = newVal;
      console.log(newVal, "newVal, ");
      // 清除之前的定时器
      if (timer) {
         clearTimeout(timer);
      }

      // 重置初始状态
      opacity.value = 0;
      loadingProgress.value = 0;

      // 设置新的定时器
      timer = setTimeout(() => {
         loadingProgress.value = 100;
         opacity.value = 1;

         setTimeout(() => {
            opacity.value = 0;
            // 等待透明度变为0后再重置进度条长度
            setTimeout(() => {
               if (opacity.value === 0) {
                  loadingProgress.value = 0;
               }
            }, 500);
         }, 500);
      }, 100);
   }
);

ruterStore.index = cgj.findTopLevelIndex(menuData.value, route.meta.breadcrumb);

// 点击路由菜单
const clickRoter = (item, index) => {
   ruterStore.index = index;
   localStorage.setItem("routerIndex", index);
   console.log(item, "item");
   emit("clickMenu", item);
   ruterStore.upLoad(item.children || item, true, item);
};

const breadcrumbs = computed(() => publicDataStore.breadcrumbs);

const isFullScreen = ref(true);
const handleClickQp = (item) => {
   isFullScreen.value = !isFullScreen.value;
   // 全屏功能
   if (!document.fullscreenElement) {
      // 进入全屏
      document.documentElement.requestFullscreen().catch((err) => {
         ElMessage.error("全屏失败: " + err.message);
      });
   } else {
      // 退出全屏
      if (document.exitFullscreen) {
         document.exitFullscreen();
      }
   }
};

const handleClose = (item) => {
   if (item.name === publicDataStore.routerName) return; // 首页不能关闭
   publicDataStore.removeBreadcrumb(item.path, router);
};

// 点击展开收缩
const clickicon = () => {
   emit("clickicon", true);
};

// 退出登录
const Logout = async () => {
   const res = await api.login.logout();
   if (res.code === 200) {
      localStorage.removeItem("token");
      localStorage.removeItem("userInfo");
      localStorage.removeItem("routerList");
      publicDataStore.clearBreadcrumbs();
      localStorage.removeItem("routerPath");
      router.replace("/login");


   } else {
      // 显示错误信息
      ElMessage.error(res.msg || "退出登录失败");
   }
};

const handleChangePassword = async () => {
   UpdatePasswordRef.value.handleDialog();
};

watchEffect(() => {
   routerIndex.value = localStorage.getItem("routerIndex") || 0;

   // 确保 menuData 有数据且索引有效
   if (menuData.value?.length > 0) {
      const targetIndex = routerIndex.value == -1 ? 0 : routerIndex.value;
      const targetItem = menuData.value[targetIndex];

      if (targetItem?.children) {
         ruterStore.upLoad(targetItem.children);
      }
   }

   // ❌ 移除这行，不要覆盖过滤后的菜单数据
   // menuData.value = ruterStore.routerList;
});

// 控制 dropdown 的显示状态
let activeDropdownIndex = ref(-1);

const handleDropdownVisibleChange = (index, visible) => {
   if (visible) {
      // 如果当前 dropdown 显示，则关闭其他 dropdown
      if (activeDropdownIndex.value !== -1 && activeDropdownIndex.value !== index) {
         // 检查 dropdownRefs 是否存在对应的元素
         if (dropdownRefs.value[activeDropdownIndex.value]) {
            dropdownRefs.value[activeDropdownIndex.value].handleClose();
         }
      }
      activeDropdownIndex.value = index;
   } else {
      // 如果当前 dropdown 隐藏，则重置 activeDropdownIndex
      if (activeDropdownIndex.value === index) {
         activeDropdownIndex.value = -1;
      }
   }
};

// 动态生成右键菜单
const getMenuDataList = (item, index) => {
   const menuItems = [];
   // 刷新页面
   menuItems.push({ title: "刷新页面", action: "refresh" });

   // 关闭左侧
   if (index > 1) {
      // 确保当前面包屑不是首页
      menuItems.push({ title: "关闭左侧", action: "closeLeft" });
   }

   // 关闭右侧
   if (index < breadcrumbs.value.length - 1) {
      menuItems.push({ title: "关闭右侧", action: "closeRight" });
   }

   // 关闭其他
   if (breadcrumbs.value.length > 1) {
      menuItems.push({ title: "关闭其他", action: "closeOthers" });
   }

   // 全部关闭
   if (breadcrumbs.value.length > 1) {
      menuItems.push({ title: "全部关闭", action: "closeAll" });
   }

   return menuItems;
};

// 处理右键菜单项点击
const handleDropdownItemClick = (action, item) => {
   switch (action) {
      case "refresh":
         publicDataStore.refreshPage(item.path, router);
         break;
      case "closeLeft":
         if (item.name !== publicDataStore.routerName) {
            publicDataStore.closeLeft(item.path, router);
         }

         break;
      case "closeRight":
         publicDataStore.closeRight(item.path, router);
         break;
      case "closeOthers":
         publicDataStore.closeOthers(item.path, router);
         break;
      case "closeAll":
         publicDataStore.closeAll(router);
         break;
   }
};
</script>

<style lang="scss" scoped>
.loading-progress {
   position: absolute;
   top: 50px;
   left: 0;
   width: 0;
   height: 2px;
   background-color: #6860ff;
   z-index: 9999;
   transition: all 0.7s ease;
   opacity: 0;
}

.sidebar {
   width: 260px; // 侧边栏宽度

   top: 0;
   left: 0;
   bottom: 0;
   background-color: #f5f8fd;
   transition: width 0.2s ease; // 平滑过渡效果
   margin-left: 20px;
   margin-right: 20px;

   .top {
      white-space: nowrap;
      display: flex;
      align-items: center;
      width: 100%;
      height: 50px;
      color: #161616;
      text-decoration: none;
      font-weight: 600;
      font-family: "黑体";
      display: flex;
      align-items: center;
      justify-content: center;
      background-color: rgb(230, 231, 238);

      &__logo {
         width: 30px;
         height: 30px;
         margin-right: 10px;
      }
   }

   .el-menu {
      border-right: none;
      height: calc(100% - 60px); // 减去顶部的高度
      overflow-y: auto; // 使菜单可滚动
   }
}

::v-deep .el-badge__content.is-fixed {
   font-size: 10px;
   right: 26px;
   padding: 0 4px;
}

::v-deep .el-menu--horizontal .el-menu-item:not(.is-disabled):hover {
   color: #6860ff;
   background-color: transparent;
}

::v-deep .el-menu-item:hover {
   // background-color: transparent;
}

::v-deep .el-menu--horizontal>.el-menu-item.is-active {
   background: #fff;
   border-radius: 8px 8px 0 0;
   border-bottom: none;
}

::v-deep .el-menu--horizontal.el-menu {
   padding-top: 12px;
   height: 50px;
}

::v-deep .el-menu-item {
   transform: translateY(1px);
}

::v-deep .el-header {
   --el-header-padding: 0 0px;
}

::v-deep .el-menu--horizontal .el-menu-item:not(.is-disabled):focus {
   background: #fff;
   border-bottom: none;
}

.header__top__right {
   // border: 1px solid red;
   width: 450px;
   height: 46px;
   transform: translateY(-1px);
   display: flex;
   align-items: center;
   justify-content: center;

   .header__top__right__left {
      display: flex;
      align-items: center;
      justify-content: center;

      .notification-badge {
         position: relative;

         .notification-icon {
            position: relative;

            &:hover {
               .tooltip {
                  opacity: 1;
                  transform: translateY(0) translateX(-60%);
                  visibility: visible;
               }

               .left_imgs {
                  transform: scale(1.15);
               }
            }

            .tooltip {
               position: absolute;
               top: 35px;
               left: 50%;
               transform: translateX(-50%) translateY(-10px);
               background-color: rgba(0, 0, 0, 0.7);
               color: white;
               padding: 4px 8px;
               border-radius: 4px;
               font-size: 12px;
               white-space: nowrap;
               z-index: 100;
               opacity: 0;
               visibility: hidden;
               transition: all 0.2s ease;
               pointer-events: none;
            }
         }
      }

      .fullscreen-icon {
         position: relative;

         &:hover {
            .tooltip {
               opacity: 1;
               transform: translateY(0) translateX(-24px);
               visibility: visible;
            }

            .left_imgs {
               transform: scale(1.15);
            }
         }

         .tooltip {
            position: absolute;
            top: 35px;
            left: 50%;
            transform: translateX(-50%) translateY(-10px);
            background-color: rgba(0, 0, 0, 0.7);
            color: white;
            padding: 4px 8px;
            border-radius: 4px;
            font-size: 12px;
            white-space: nowrap;
            z-index: 100;
            opacity: 0;
            visibility: hidden;
            transition: all 0.2s ease;
            pointer-events: none;
         }
      }

      .left_imgs {
         width: 20px;
         height: 20px;
         margin-right: 20px;
         cursor: pointer;
         transition: transform 0.2s ease;
      }
   }

   .header__top__right__right {
      display: flex;
      align-items: center;
      justify-content: center;
      font-size: 12px;

      .avatar-container {
         position: relative;
         margin-right: 20px;

         &:hover {
            .avatar-preview {
               opacity: 1;
               transform: translateY(0) scale(1) translateX(-51%);
               visibility: visible;
            }
         }

         .avatar-preview {
            position: absolute;
            top: 45px;
            left: 80%;
            transform: translateX(-50%) translateY(-10px) scale(0.95);
            background-color: white;
            border-radius: 8px;
            box-shadow: 0 4px 12px rgba(0, 0, 0, 0.15);
            padding: 6px;
            z-index: 100;
            opacity: 0;
            visibility: hidden;
            transition: all 0.3s cubic-bezier(0.23, 1, 0.32, 1);
            pointer-events: none; // 防止鼠标事件干扰

            &::before {
               content: "";
               position: absolute;
               top: -8px;
               left: 50%;
               transform: translateX(-50%);
               border-width: 0 8px 8px;
               border-style: solid;
               border-color: transparent transparent white;
            }

            img {
               width: 140px;
               height: 140px;
               border-radius: 4px;
               object-fit: cover;
               display: block; // 防止图片底部间隙
            }
         }
      }

      .username-container {
         position: relative;
         cursor: pointer;

         &:hover {
            .user-menu {
               opacity: 1;
               transform: translateY(0) translateX(30%);
               visibility: visible;
            }

            .hoverShow {
               color: #6860ff;
            }
         }

         .hoverShow {
            transition: color 0.2s ease;
         }

         .user-menu {
            position: absolute;
            top: 30px;
            right: 0;
            background-color: white;
            border-radius: 4px;
            box-shadow: 0 2px 12px rgba(0, 0, 0, 0.1);
            padding: 5px 0;
            z-index: 100;
            opacity: 0;
            visibility: hidden;
            transform: translateY(-10px);
            transition: all 0.3s cubic-bezier(0.23, 1, 0.32, 1);
            min-width: 120px;

            .menu-item {
               padding: 8px 16px;
               font-size: 14px;
               color: #333;
               transition: background-color 0.2s;

               &:hover {
                  background-color: #f5f7fa;
                  color: #6860ff;
               }
            }
         }
      }
   }

   .header__top__right__right__img {
      width: 30px;
      height: 30px;
      border-radius: 50%;
      cursor: pointer;
      transition: transform 0.3s ease;

      &:hover {
         transform: scale(1.1);
      }
   }
}

.header {
   width: 100%;
   height: 50px !important;
   padding: 0px;

   &__top {
      width: 100%;
      display: flex;
      align-items: center;
      justify-content: space-between;
      height: 50px; // 保持顶部的高度

      // margin-bottom: 8px;
      &__left {
         width: 100%;
         display: flex;
         align-items: center;

         &__txt {
            width: 100%;
            margin-left: 50px;
         }
      }
   }

   &__bottom {
      width: 100%;
      height: 30px; // 保持底部的高度
      display: flex;
      background-color: #fff;

      .el-breadcrumb {
         height: 100%;
         line-height: 30px; // 使面包屑垂直居中
      }
   }

   .user-dropdown {
      width: 100px;
      display: flex;
      align-items: center;
      cursor: pointer;
      padding: 8px 20px;
      border-radius: 10px;
      transition: background-color 0.3s;

      &:hover {
         background-color: transparent; // 悬停背景色
      }

      .user-name {
         margin-left: 8px;
         margin-right: 8px;
         font-size: 14px;
         color: #606266;
      }
   }
}
</style>
